<template>
  <van-nav-bar :title="t('inbound.fastInbound')" left-arrow @click-left="onClickLeft" placeholder fixed />
  <div v-if="showSn == 1">
    <van-cell-group>
      <van-row v-if="!loading" gutter="10" class="van-cell van-cell--center">
        <van-col span="18">
          <van-row class="van-cell__title">{{ t('inbound.orderNo') + orderInfo.orderNo }}</van-row>
          <van-row class="van-cell__label">{{ t('inbound.customer') + orderInfo.customerCodeAndName }}</van-row>
        </van-col>
        <van-col span="6" class="van-cell__value">
          <span>{{ orderInfo.receiptBoxNum + '/' + orderInfo.boxNum }}</span>
        </van-col>
      </van-row>
    </van-cell-group>
    <van-field ref="boxNoRef" v-model="boxNo" size="large" @keydown.enter="handleScanBox"
      :placeholder="t('inbound.pleaseScanBoxNo')" clearable>
      <template #left-icon>
        <van-icon name="enlarge" size="1.5rem" class="px-2" />
      </template>
    </van-field>
    <van-cell-group class="p-2">
      <van-empty v-if="finished && orderInfo.orderInfoBoxDTOList?.length <= 0" :description="t('inbound.allInbound')" />
      <van-list v-if="showSn == 1" v-model:loading="loading" :finished="finished" :loading-text="t('loading')"
        @load="onLoad">
        <van-cell v-for="(item, i) in orderInfo.orderInfoBoxDTOList" :key="i" :title="t('inbound.boxNo') + item.boxNo"
          @click="showDetail(item)">
          <template #label>
            <van-row gutter="10">
              <van-col span="12">{{ t('inbound.skuType') + item.skuTypeNum }}</van-col>
              <van-col span="12" class="text-right">{{ t('inbound.skuNum') + item.boxPreNum }}</van-col>
            </van-row>
          </template>
        </van-cell>
      </van-list>
    </van-cell-group>
  </div>
  <div v-if="showSn == 2">
    <van-cell-group>
      <van-cell center>
        <template #title>
          <van-row>{{ t('inbound.orderNo') + orderInfo.orderNo }}</van-row>
          <van-row>{{ t('inbound.boxNo') + currentBox.boxNo }}</van-row>
        </template>
        <template #value>
          <van-checkbox class="float-right" v-model="currentBox.originalBox" shape="square">{{ t('inbound.originalBox')
          }}</van-checkbox>
        </template>
      </van-cell>
    </van-cell-group>
    <van-field ref="skuCodeRef" v-model="skuCode" size="large" @keydown.enter="handleScanSku"
      :placeholder="t('inbound.pleaseScanSku')" clearable>
      <template #left-icon>
        <van-icon name="enlarge" size="1.5rem" class="px-2" />
      </template>
    </van-field>
    <van-tabs v-model:active="activeTab" line-width="50%" swipeable>
      <van-tab :title="t('inbound.box')">
        <van-cell :title="t('inbound.preNum')" :value="currentBox.boxPreNum" />
        <van-field name="size" required label-align="top">
          <template #label>
            <van-row class="w-full" gutter="10">
              <van-col span="14">
                {{ t('inbound.realSize') }}
              </van-col>
              <van-col span="10" class="text-right text-gray-500">
                {{ currentBox.boxLength }} * {{ currentBox.boxWidth }} * {{ currentBox.boxHeight }} CM
              </van-col>
            </van-row>
          </template>
          <template #input>
            <van-row gutter="10">
              <van-col span="7">
                <van-field v-model="currentBox.realLength" clearable class="input-border" />
              </van-col>
              <van-col span="7">
                <van-field v-model="currentBox.realWidth" clearable class="input-border" />
              </van-col>
              <van-col span="10">
                <van-field v-model="currentBox.realHeight" clearable class="input-border">
                  <template #right-icon>
                    CM
                  </template>
                </van-field>
              </van-col>
            </van-row>
          </template>
        </van-field>
        <van-field name="weight" required label-align="top">
          <template #label>
            <van-row class="w-full" gutter="10">
              <van-col span="14">
                {{ t('inbound.realWeight') }}
              </van-col>
              <van-col span="10" class="text-right text-gray-500">
                {{ currentBox.boxWeight }} KG
              </van-col>
            </van-row>
          </template>
          <template #input>
            <van-field v-model="currentBox.realWeight" clearable class="input-border">
              <template #right-icon>
                KG
              </template>
            </van-field>
          </template>
        </van-field>
        <van-field v-if="currentBox.originalBox" :label="t('inbound.locationCode')" name="locationCode" required
          label-align="top">
          <template #input>
            <van-field v-model="currentBox.locationCode" :placeholder="t('inbound.pleaseScanLocation')" clearable
              class="input-border">
              <template #left-icon>
                <van-icon name="enlarge" size="1.5rem" class="pr-2" />
              </template>
            </van-field>
          </template>
        </van-field>
      </van-tab>
      <van-tab title="SKU">
        <van-collapse v-model="currentSkuIndex" accordion>
          <van-collapse-item v-for="(sku, i) in currentBox.orderInfoBoxSkuDTOList" :key="i" :name="i">
            <template #title>
              <span class="font-bold">{{ sku.skuCode }}</span>
              <span class="ml-3">{{ sku.receiveStatus === 0 ? t('enums.receiveStatus.firstArrival') :
                t('enums.receiveStatus.toTheWarehouseAgain') }}</span>
            </template>
            <van-field v-model="sku.packagingTypeText" is-link readonly :label="t('inbound.packagingType')"
              name="packagingType" :required="!currentBox.originalBox" @click="showPackagingType = true" />
            <van-field name="realNum" :required="!currentBox.originalBox" label-align="top">
              <template #label>
                <van-row class="w-full" gutter="10">
                  <van-col span="14">
                    {{ t('inbound.receiptNum') }}
                  </van-col>
                  <van-col span="10" class="text-right text-gray-500">
                    {{ sku.receiptNum }} / {{ sku.preSkuNum }}
                  </van-col>
                </van-row>
              </template>
              <template #input>
                <van-field v-model="sku.realNum" type="digit" clearable class="input-border" />
              </template>
            </van-field>
            <van-field name="size" :required="!currentBox.originalBox" label-align="top">
              <template #label>
                <van-row class="w-full" gutter="10">
                  <van-col span="14">
                    {{ t('inbound.realSize') }}
                  </van-col>
                  <van-col span="10" class="text-right text-gray-500">
                    {{ sku.skuLength }} * {{ sku.skuWidth }} * {{ sku.skuHeight }} CM
                  </van-col>
                </van-row>
              </template>
              <template #input>
                <van-row gutter="10">
                  <van-col span="7">
                    <van-field v-model="sku.realLength" clearable class="input-border" />
                  </van-col>
                  <van-col span="7">
                    <van-field v-model="sku.realWidth" clearable class="input-border" />
                  </van-col>
                  <van-col span="10">
                    <van-field v-model="sku.realHeight" clearable class="input-border">
                      <template #right-icon>
                        CM
                      </template>
                    </van-field>
                  </van-col>
                </van-row>
              </template>
            </van-field>
            <van-field name="weight" :required="!currentBox.originalBox" label-align="top">
              <template #label>
                <van-row class="w-full" gutter="10">
                  <van-col span="14">
                    {{ t('inbound.realWeight') }}
                  </van-col>
                  <van-col span="10" class="text-right text-gray-500">
                    {{ sku.skuWeight }} KG
                  </van-col>
                </van-row>
              </template>
              <template #input>
                <van-field v-model="sku.realWeight" clearable class="input-border">
                  <template #right-icon>
                    KG
                  </template>
                </van-field>
              </template>
            </van-field>
            <van-field v-if="!currentBox.originalBox" :label="t('inbound.locationCode')" name="locationCode" required
              label-align="top">
              <template #input>
                <van-field v-model="sku.locationCode" :placeholder="t('inbound.pleaseScanLocation')" clearable
                  class="input-border">
                  <template #left-icon>
                    <van-icon name="enlarge" size="1.5rem" class="pr-2" />
                  </template>
                </van-field>
              </template>
            </van-field>
            <van-field v-if="!currentBox.originalBox" v-model="sku.selectLocationCode" is-link readonly
              :label="t('inbound.referLocationCode')" name="referLocationCode" @click="openReferLocation" />
          </van-collapse-item>
        </van-collapse>
      </van-tab>
    </van-tabs>
    <van-action-bar placeholder>
      <van-row gutter="10" class="w-full p-1">
        <van-col span="12">
          <van-button class="text-base" block plain @click="showSn -= 1">{{ t('cancel') }}</van-button>
        </van-col>
        <van-col span="12">
          <van-button class="text-base" :loading="confirmLoading" block type="primary" @click="confirmInbound">{{
            t('inbound.inboundConfirm') }}</van-button>
        </van-col>
      </van-row>
    </van-action-bar>
  </div>
  <van-back-top />
  <van-popup v-model:show="showPackagingType" position="bottom">
    <van-picker :confirm-button-text="t('confirm')" :cancel-button-text="t('cancel')" :columns="packagingTypeEnums"
      @confirm="selectPackagingType" @cancel="showPackagingType = false" />
  </van-popup>
  <van-popup v-model:show="showReferLocation" position="bottom">
    <van-picker :confirm-button-text="t('confirm')" :cancel-button-text="t('cancel')" :columns="referLocations"
      @confirm="selectLocation" @cancel="showReferLocation = false" />
  </van-popup>
</template>

<script setup lang="ts">
import { useI18n } from "vue-i18n";
import { postRequest, scanSuccess, scanFail } from "@/api";
import { useRoute } from "vue-router";
import { AppToast } from "@/utils/appToast";
import { showConfirmDialog } from "vant";
import { STORAGE_LANG_KEY } from '@/stores/mutation-type'
const isRu = localStorage.getItem(STORAGE_LANG_KEY) === 'ru-RU'

const query = useRoute().query;
const { t } = useI18n();
const onClickLeft = () => {
  showSn.value -= 1
  nextTick(() => boxNoRef.value.focus())
  if (!showSn.value) {
    history.back();
  }
}
const showSn = ref(1);
const loading = ref(false);
const confirmLoading = ref(false);
const finished = ref(false);
const showPackagingType = ref(false);
const showReferLocation = ref(false);
const orderInfo: any = ref({});
const boxNo = ref();
const boxNoRef = ref();
const skuCode = ref();
const skuCodeRef = ref();
const activeTab = ref(0);

const currentBox = ref();
const currentSkuIndex = ref(0);

const packagingTypeEnums = [
  { text: t('enums.packagingType.withShippingBox'), value: 0 },
  { text: t('enums.packagingType.withTransportPackages'), value: 1 },
  { text: t('enums.packagingType.noTransportPackaging'), value: 2 }
];

const referLocations = ref([]);

onMounted(() => {
  boxNoRef.value.focus()
});

const onLoad = () => {
  postRequest("/orderInfo/getReceiveOrderInfoByNo", { number: query.orderNo }).then(res => {
    res.data.orderInfoBoxDTOList.filter(box => box.boxStatus === 0).forEach(box => {
      box.realLength = box.boxLength
      box.realWidth = box.boxWidth
      box.realHeight = box.boxHeight
      box.realWeight = box.boxWeight
      box.orderInfoBoxSkuDTOList.forEach(sku => {
        if (sku.receiveStatus !== 0) {
          sku.realLength = sku.skuLength
          sku.realWidth = sku.skuWidth
          sku.realHeight = sku.skuHeight
          sku.realWeight = sku.skuWeight
        }
        sku.packagingTypeText = packagingTypeEnums.find(packagingType => packagingType.value === sku.packagingType)?.text
        if (sku.referLocationCode) {
          sku.selectLocationCode = sku.referLocationCode[0]?.locationCode
        }
      })
    })
    orderInfo.value = res.data;
  }).finally(() => {
    loading.value = false;
    finished.value = true;
  })
};

const handleScanBox = () => {
  const box = orderInfo.value.orderInfoBoxDTOList.find(item => item.boxNo.toLowerCase() === boxNo.value.toLowerCase())
  console.log('box', box)
  if (box) {
    scanSuccess()
    currentBox.value = box
    showDetail(box)
  } else {
    scanFail();
  }
  boxNo.value = null
};

const handleScanSku = () => {
  const index = currentBox.value.orderInfoBoxSkuDTOList.findIndex(item => item.skuCode.toLowerCase() === skuCode.value.toLowerCase())
  if (index >= 0) {
    activeTab.value = 1
    currentSkuIndex.value = index
    const sku = currentBox.value.orderInfoBoxSkuDTOList[index]
    sku.realNum = parseInt(sku.realNum || 0) + 1
    scanSuccess()
  } else {
    scanFail();
  }
  skuCode.value = null
};

const showDetail = (box) => {
  showSn.value = 2;
  activeTab.value = 0
  currentSkuIndex.value = 0
  currentBox.value = box;
  nextTick(() => skuCodeRef.value.focus())
}

const selectPackagingType = ({ selectedOptions }) => {
  currentBox.value.orderInfoBoxSkuDTOList[currentSkuIndex.value].packagingType = selectedOptions[0]?.value;
  currentBox.value.orderInfoBoxSkuDTOList[currentSkuIndex.value].packagingTypeText = selectedOptions[0]?.text;
  showPackagingType.value = false;
};

const openReferLocation = () => {
  referLocations.value = currentBox.value.orderInfoBoxSkuDTOList[currentSkuIndex.value].referLocationCode?.map(item => {
    return {
      value: item.locationCode,
      text: item.locationCode,
    }
  }) || []
  showReferLocation.value = true;
};

const selectLocation = ({ selectedOptions }) => {
  currentBox.value.orderInfoBoxSkuDTOList[currentSkuIndex.value].selectLocationCode = selectedOptions[0]?.text;
  showReferLocation.value = false;
};

const validateBox = (box: any) => {
  return (!box.originalBox) || (box.realLength > 0 && box.realWidth > 0 && box.realHeight > 0 && box.realWeight > 0 && (!box.originalBox || box.locationCode))
}

const validateSku = (box: any, sku: any) => {
  return box.originalBox || (sku.packagingType != null && sku.realLength > 0 && sku.realWidth > 0 && sku.realHeight > 0 && sku.realWeight > 0 && sku.realNum >= 0 && sku.locationCode)
}

const confirmInbound = () => {
  const request = {
    fromTerminal: 1,
    orderId: orderInfo.value.orderId,
    orderInfoForReceiptList: []
  }
  if (!validateBox(currentBox.value)) {
    activeTab.value = 0
    AppToast(t("pleaseCheckRequired"), "danger", true);
    confirmLoading.value = false
    return
  }
  const infoArr = [];
  for (let i = 0; i < currentBox.value.orderInfoBoxSkuDTOList.length; i++) {
    const sku = currentBox.value.orderInfoBoxSkuDTOList[i]
    if (!validateSku(currentBox.value, sku)) {
      activeTab.value = 1
      currentSkuIndex.value = i
      AppToast(t("pleaseCheckRequired"), "danger", true);
      confirmLoading.value = false
      return
    }

    request.orderInfoForReceiptList.push({
      boxId: currentBox.value.boxId,
      boxLength: currentBox.value.realLength,
      boxWidth: currentBox.value.realWidth,
      boxHeight: currentBox.value.realHeight,
      boxWeight: currentBox.value.realWeight,
      skuId: sku.skuId,
      packagingType: sku.packagingType,
      skuLength: sku.realLength,
      skuWidth: sku.realWidth,
      skuHeight: sku.realHeight,
      skuWeight: sku.realWeight,
      receiptNum: sku.realNum,
      originalBox: currentBox.value.originalBox ? 1 : 0,
      locationCode: currentBox.value.originalBox ? currentBox.value.locationCode : sku.locationCode
    })
    if (Number(sku.realNum) > Number(sku.preSkuNum)) {
      infoArr.push(`${isRu ? '【' : ''}${t('inbound.receiptNum')?.replace('：', '')}>${t('inbound.preSkuNum')}${isRu ? '' : '】'}`)
    } else if (Number(sku.realNum) < Number(sku.preSkuNum)) {
      infoArr.push(`${isRu ? '【' : ''}${t('inbound.receiptNum')?.replace('：', '')}<${t('inbound.preSkuNum')}${isRu ? '' : '】'}`)
    }
  }
  if (infoArr.length > 0) {
    showConfirmDialog({
      message: infoArr[0],
      confirmButtonText: t("confirm"),
      cancelButtonText: t("cancel"),
    })
      .then(() => {
        submit(request)
        return;
      })
      .catch(() => {
        // on cancel
      })
  } else {
    submit(request)
  }

}
const submit = (request) => {
  confirmLoading.value = true
  postRequest('/orderInfo/updateOrderInfoForQuickReceipt', request).then(() => {
    AppToast(t("inbound.inboundSuccess"), "success")
    orderInfo.value.orderInfoBoxDTOList.splice(orderInfo.value.orderInfoBoxDTOList.indexOf(currentBox.value), 1);
    showSn.value = 1
    nextTick(() => boxNoRef.value.focus())
  }).finally(() => {
    confirmLoading.value = false
  })
}
</script>

<style scoped lang="less">
:deep(.van-cell) {
  font-size: 1rem;
}

:deep(.van-nav-bar__title) {
  font-size: 1rem;
  font-weight: 500;
  color: white;
}

:deep(.van-nav-bar__content) {
  background: #1b82d2;
}

:deep(.van-nav-bar .van-icon) {
  color: white;
}

:deep(.van-collapse-item__content) {
  padding: 0;
}

:deep(.input-border) {
  border: 1px solid #e5e7eb;
}
</style>
